{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from concurrent.futures import ThreadPoolExecutor\n",
    "from glob import glob\n",
    "from pathlib import Path\n",
    "from pprint import pprint\n",
    "import threading\n",
    "\n",
    "\n",
    "from dotenv import load_dotenv\n",
    "from langchain.globals import set_llm_cache\n",
    "from langchain_core.caches import InMemoryCache\n",
    "import pandas as pd\n",
    "import promptquality as pq\n",
    "from tqdm.auto import tqdm\n",
    "from llm_handler import LLMHandler\n",
    "\n",
    "from IPython.display import clear_output\n",
    "\n",
    "set_llm_cache(InMemoryCache())\n",
    "\n",
    "load_dotenv(\"../.env\")\n",
    "# pq.login(\"console.demo.rungalileo.io\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "llm_handler = LLMHandler()\n",
    "model = \"accounts/fireworks/models/deepseek-r1\"\n",
    "llm = llm_handler.get_llm(model, temperature=0.0, max_tokens=4000)\n",
    "# llm.invoke(\"Hello, how are you?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "files = glob(\"../data/datasets/*.parquet\")\n",
    "print(len(files))\n",
    "files"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import re\n",
    "from pydantic import BaseModel\n",
    "from openai import OpenAI\n",
    "import os\n",
    "\n",
    "from dotenv import load_dotenv\n",
    "load_dotenv(\"../.env\")\n",
    " \n",
    "# Initialize the Fireworks client\n",
    "client = OpenAI(\n",
    "    base_url=\"https://api.fireworks.ai/inference/v1\",\n",
    "    api_key=os.getenv(\"FIREWORKS_API_KEY\"),\n",
    ")\n",
    " \n",
    " \n",
    "# Define the output schema using Pydantic\n",
    "class QAResult(BaseModel):\n",
    "    question: str\n",
    "    answer: str\n",
    " \n",
    " \n",
    "# Prepare the user input\n",
    "user_input = \"Who wrote 'Pride and Prejudice'?\"\n",
    " \n",
    "# Construct the messages payload\n",
    "messages = [{\"role\": \"user\", \"content\": user_input}]\n",
    " \n",
    "# Make the API call to DeepSeek R1\n",
    "response = client.chat.completions.create(\n",
    "    model=\"accounts/fireworks/models/deepseek-r1\",\n",
    "    messages=messages,\n",
    "    response_format={\"type\": \"json_object\", \"schema\": QAResult.model_json_schema()},\n",
    "    max_tokens=1000,  # Adjust as needed to prevent truncation\n",
    ")\n",
    " \n",
    "# Extract the content of the response\n",
    "response_content = response.choices[0].message.content\n",
    "print(f\"Response content: {response_content}\")\n",
    " \n",
    "# Use regular expressions to extract the reasoning and JSON parts.\n",
    "# The reasoning is enclosed within <think>...</think> tags,\n",
    "# and the JSON part follows the </think> tag.\n",
    "reasoning_match = re.search(r\"<think>(.*?)</think>\", response_content, re.DOTALL)\n",
    "json_match = re.search(r\"</think>\\s*(\\{.*\\})\", response_content, re.DOTALL)\n",
    " \n",
    "# Extract reasoning\n",
    "reasoning = reasoning_match.group(1).strip()\n",
    " \n",
    "# Extract JSON string\n",
    "json_str = json_match.group(1).strip()\n",
    " \n",
    "# Directly parse the JSON string into a Pydantic model\n",
    "qa_result = QAResult.model_validate_json(json_str)\n",
    " \n",
    "# Output the extracted reasoning and the parsed Pydantic model\n",
    "print(f\"\\nReasoning: {reasoning}\")\n",
    "print(f\"\\nQAResult: {qa_result}\")\n",
    " "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import re\n",
    "from typing import TypedDict, Any, Union, List\n",
    "from pydantic import BaseModel\n",
    "from openai import OpenAI\n",
    "import os\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "load_dotenv(\"../.env\")\n",
    "\n",
    "# Tool call schema\n",
    "class ToolCall(TypedDict):\n",
    "    name: str\n",
    "    args: dict[str, Any]\n",
    "\n",
    "# Define possible response types using Pydantic\n",
    "class TextResponse(BaseModel):\n",
    "    text: str\n",
    "\n",
    "class ToolCallResponse(BaseModel):\n",
    "    tool_calls: List[ToolCall]\n",
    "\n",
    "class CombinedResponse(BaseModel):\n",
    "    response_type: str  # Either \"text\" or \"tool_calls\"\n",
    "    content: Union[TextResponse, List[ToolCall]]\n",
    "\n",
    "# Initialize the Fireworks client\n",
    "client = OpenAI(\n",
    "    base_url=\"https://api.fireworks.ai/inference/v1\",\n",
    "    api_key=os.getenv(\"FIREWORKS_API_KEY\"),\n",
    ")\n",
    "\n",
    "def process_llm_response(user_input: str, response_type: str = \"text\") -> CombinedResponse:\n",
    "    \"\"\"\n",
    "    Process LLM response with support for both text and tool calls\n",
    "    \n",
    "    Args:\n",
    "        user_input: The user's question or command\n",
    "        response_type: Either \"text\" or \"tool_calls\" to specify expected response format\n",
    "    \n",
    "    Returns:\n",
    "        CombinedResponse object containing either text response or tool calls\n",
    "    \"\"\"\n",
    "    # Construct the messages payload\n",
    "    messages = [{\"role\": \"user\", \"content\": user_input}]\n",
    "    \n",
    "    # Set up the response schema based on the requested type\n",
    "    if response_type == \"text\":\n",
    "        schema = TextResponse.model_json_schema()\n",
    "    else:\n",
    "        schema = ToolCallResponse.model_json_schema()\n",
    "    \n",
    "    # Make the API call to DeepSeek R1\n",
    "    response = client.chat.completions.create(\n",
    "        model=\"accounts/fireworks/models/deepseek-r1\",\n",
    "        messages=messages,\n",
    "        response_format={\"type\": \"json_object\", \"schema\": schema},\n",
    "        max_tokens=1000,\n",
    "    )\n",
    "    \n",
    "    # Extract the content of the response\n",
    "    response_content = response.choices[0].message.content\n",
    "    \n",
    "    # Parse the response using regex\n",
    "    reasoning_match = re.search(r\"<think>(.*?)</think>\", response_content, re.DOTALL)\n",
    "    json_match = re.search(r\"</think>\\s*(\\{.*\\})\", response_content, re.DOTALL)\n",
    "    \n",
    "    if not reasoning_match or not json_match:\n",
    "        raise ValueError(\"Invalid response format from LLM\")\n",
    "    \n",
    "    reasoning = reasoning_match.group(1).strip()\n",
    "    json_str = json_match.group(1).strip()\n",
    "    \n",
    "    # Parse the JSON response based on the type\n",
    "    if response_type == \"text\":\n",
    "        content = TextResponse.model_validate_json(json_str)\n",
    "    else:\n",
    "        content = ToolCallResponse.model_validate_json(json_str)\n",
    "        content = content.tool_calls  # Extract just the tool calls list\n",
    "    \n",
    "    return CombinedResponse(\n",
    "        response_type=response_type,\n",
    "        content=content\n",
    "    )\n",
    "\n",
    "# # Example usage\n",
    "# if __name__ == \"__main__\":\n",
    "#     # Example text response\n",
    "#     text_question = \"Who wrote 'Pride and Prejudice'?\"\n",
    "#     text_result = process_llm_response(text_question, \"text\")\n",
    "#     print(f\"\\nText Response: {text_result}\")\n",
    "    \n",
    "#     # Example tool call response\n",
    "#     tool_question = \"Calculate 15% of 85\"\n",
    "#     tool_result = process_llm_response(tool_question, \"tool_calls\")\n",
    "#     print(f\"\\nTool Call Response: {tool_result}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "CombinedResponse.model_json_schema()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_parquet(files[0], engine=\"fastparquet\")\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Your job is to use the given tools to answer the query of human. If there is no relevant tool then reply with 'I cannot answer the question with given tools'. If tool is available but sufficient information is not available, then ask human to get the same. You can call as many tools as you want. Use multiple tools if needed. If the tools need to be called in a sequence then just call the first tool. The final response after thinking should **only** be a list of tools or single tool that you would call and or just a text message if not tool call is possible. Here is the schema for the output which can be just text response or a list of tool call. \n",
      "{'$defs': {'TextResponse': {'properties': {'text': {'title': 'Text', 'type': 'string'}}, 'required': ['text'], 'title': 'TextResponse', 'type': 'object'}, 'ToolCall': {'properties': {'name': {'title': 'Name', 'type': 'string'}, 'args': {'title': 'Args', 'type': 'object'}}, 'required': ['name', 'args'], 'title': 'ToolCall', 'type': 'object'}}, 'properties': {'response_type': {'title': 'Response Type', 'type': 'string'}, 'content': {'anyOf': [{'$ref': '#/$defs/TextResponse'}, {'items': {'$ref': '#/$defs/ToolCall'}, 'type': 'array'}], 'title': 'Content'}}, 'required': ['response_type', 'content'], 'title': 'CombinedResponse', 'type': 'object'}\n",
      "\n",
      "I'm about to embark on a road trip adventure and I want my car to be in peak condition. Could you make sure to increase the current fuel level to ensure that my tank is full, so I don't have to keep stopping to refuel along the way?\n",
      "I want to make certain my tires are roadworthy before setting off. If any of my car's tires are showing pressure below 40, point me in the direction of the closest tire service station, because I definitely don't want to run into tire trouble. [{'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: Add a contact to the workspace.', 'properties': {'user_name': {'description': 'User name of contact to be added.', 'type': 'string', 'title': 'User_Name'}}, 'required': ['user_name'], 'title': 'add_contact', 'type': 'object'}, {'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: Delete the latest message sent to a receiver.', 'properties': {'receiver_id': {'description': 'User ID of the user to send the message to.', 'type': 'string', 'title': 'Receiver_Id'}, 'message_id': {'description': 'ID of the message to be deleted.', 'type': 'integer', 'title': 'Message_Id'}}, 'required': ['receiver_id'], 'title': 'delete_message', 'type': 'object'}, {'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: Get statistics about messages for the current user.', 'properties': {}, 'required': [], 'title': 'get_message_stats', 'type': 'object'}, {'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: Get user ID from user name.', 'properties': {'user': {'description': 'User name of the user. ', 'type': 'string', 'title': 'User'}}, 'required': ['user'], 'title': 'get_user_id', 'type': 'object'}, {'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: List all users in the workspace.', 'properties': {}, 'required': [], 'title': 'list_users', 'type': 'object'}, {'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: Get the login status of the current user.', 'properties': {}, 'required': [], 'title': 'message_get_login_status', 'type': 'object'}, {'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: Log in a user with the given user ID to messeage application.', 'properties': {'user_id': {'description': 'User ID of the user to log in. ', 'type': 'string', 'title': 'User_Id'}}, 'required': ['user_id'], 'title': 'message_login', 'type': 'object'}, {'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: Search for messages containing a specific keyword.', 'properties': {'keyword': {'description': 'The keyword to search for in messages.', 'type': 'string', 'title': 'Keyword'}}, 'required': ['keyword'], 'title': 'search_messages', 'type': 'object'}, {'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: Send a message to a user.', 'properties': {'receiver_id': {'description': 'User ID of the user to send the message to.', 'type': 'string', 'title': 'Receiver_Id'}, 'message': {'description': 'Message to be sent.', 'type': 'string', 'title': 'Message'}}, 'required': ['receiver_id', 'message'], 'title': 'send_message', 'type': 'object'}, {'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: View all historical messages sent by the current user.', 'properties': {}, 'required': [], 'title': 'view_messages_sent', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Add a stock to the watchlist.', 'properties': {'stock': {'description': 'the stock symbol to add to the watchlist. ', 'type': 'string', 'title': 'Stock'}}, 'required': ['stock'], 'title': 'add_to_watchlist', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Cancel an order.', 'properties': {'order_id': {'description': 'ID of the order to cancel. ', 'type': 'integer', 'title': 'Order_Id'}}, 'required': ['order_id'], 'title': 'cancel_order', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Filter stocks based on a price range.', 'properties': {'stocks': {'description': 'List of stock symbols to filter.', 'type': 'array', 'items': {'type': 'string'}, 'title': 'Stocks'}, 'min_price': {'description': 'Minimum stock price.', 'type': 'number', 'title': 'Min_Price'}, 'max_price': {'description': 'Maximum stock price. ', 'type': 'number', 'title': 'Max_Price'}}, 'required': ['stocks', 'min_price', 'max_price'], 'title': 'filter_stocks_by_price', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Fund the account with the specified amount.', 'properties': {'amount': {'description': 'Amount to fund the account with. ', 'type': 'number', 'title': 'Amount'}}, 'required': ['amount'], 'title': 'fund_account', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get account information.', 'properties': {}, 'required': [], 'title': 'get_account_info', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get a list of stock symbols in the given sector.', 'properties': {'sector': {'description': \"The sector to retrieve stocks from (e.g., 'Technology'). \", 'type': 'string', 'title': 'Sector'}}, 'required': ['sector'], 'title': 'get_available_stocks', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get the current time.', 'properties': {}, 'required': [], 'title': 'get_current_time', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get the details of an order.', 'properties': {'order_id': {'description': 'ID of the order. ', 'type': 'integer', 'title': 'Order_Id'}}, 'required': ['order_id'], 'title': 'get_order_details', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get the stock order ID history.', 'properties': {}, 'required': [], 'title': 'get_order_history', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get the details of a stock.', 'properties': {'symbol': {'description': 'Symbol that uniquely identifies the stock. ', 'type': 'string', 'title': 'Symbol'}}, 'required': ['symbol'], 'title': 'get_stock_info', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get the symbol of a stock by company name.', 'properties': {'name': {'description': 'Name of the company. ', 'type': 'string', 'title': 'Name'}}, 'required': ['name'], 'title': 'get_symbol_by_name', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get the transaction history within a specified date range.', 'properties': {'start_date': {'description': \"Start date for the history (format: 'YYYY-MM-DD').\", 'type': 'string', 'title': 'Start_Date'}, 'end_date': {'description': \"End date for the history (format: 'YYYY-MM-DD'). \", 'type': 'string', 'title': 'End_Date'}}, 'required': [], 'title': 'get_transaction_history', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get the watchlist.', 'properties': {}, 'required': [], 'title': 'get_watchlist', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Make a deposit or withdrawal based on specified amount.', 'properties': {'account_id': {'description': 'ID of the account.', 'type': 'integer', 'title': 'Account_Id'}, 'xact_type': {'description': 'Transaction type (deposit or withdrawal).', 'type': 'string', 'title': 'Xact_Type'}, 'amount': {'description': 'Amount to deposit or withdraw. ', 'type': 'number', 'title': 'Amount'}}, 'required': ['account_id', 'xact_type', 'amount'], 'title': 'make_transaction', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Notify if there is a significant price change in the stocks.', 'properties': {'stocks': {'description': 'List of stock symbols to check.', 'type': 'array', 'items': {'type': 'string'}, 'title': 'Stocks'}, 'threshold': {'description': 'Percentage change threshold to trigger a notification. ', 'type': 'number', 'title': 'Threshold'}}, 'required': ['stocks', 'threshold'], 'title': 'notify_price_change', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Place an order.', 'properties': {'order_type': {'description': 'Type of the order (Buy/Sell).', 'type': 'string', 'title': 'Order_Type'}, 'symbol': {'description': 'Symbol of the stock to trade.', 'type': 'string', 'title': 'Symbol'}, 'price': {'description': 'Price at which to place the order.', 'type': 'number', 'title': 'Price'}, 'amount': {'description': 'Number of shares to trade. ', 'type': 'integer', 'title': 'Amount'}}, 'required': ['order_type', 'symbol', 'price', 'amount'], 'title': 'place_order', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Remove a stock from the watchlist.', 'properties': {'symbol': {'description': 'Symbol of the stock to remove. ', 'type': 'string', 'title': 'Symbol'}}, 'required': ['symbol'], 'title': 'remove_stock_from_watchlist', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get the login status.', 'properties': {}, 'required': [], 'title': 'trading_get_login_status', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Handle user login.', 'properties': {'username': {'description': 'Username for authentication.', 'type': 'string', 'title': 'Username'}, 'password': {'description': 'Password for authentication. ', 'type': 'string', 'title': 'Password'}}, 'required': ['username', 'password'], 'title': 'trading_login', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Handle user logout for trading system.', 'properties': {}, 'required': [], 'title': 'trading_logout', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Update the market status based on the current time.', 'properties': {'current_time_str': {'description': 'Current time in HH:MM AM/PM format. ', 'type': 'string', 'title': 'Current_Time_Str'}}, 'required': ['current_time_str'], 'title': 'update_market_status', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Update the price of a stock.', 'properties': {'symbol': {'description': 'Symbol of the stock to update.', 'type': 'string', 'title': 'Symbol'}, 'new_price': {'description': 'New price of the stock. ', 'type': 'number', 'title': 'New_Price'}}, 'required': ['symbol', 'new_price'], 'title': 'update_stock_price', 'type': 'object'}] [{'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: Add a contact to the workspace.', 'properties': {'user_name': {'description': 'User name of contact to be added.', 'type': 'string', 'title': 'User_Name'}}, 'required': ['user_name'], 'title': 'add_contact', 'type': 'object'}, {'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: Delete the latest message sent to a receiver.', 'properties': {'receiver_id': {'description': 'User ID of the user to send the message to.', 'type': 'string', 'title': 'Receiver_Id'}, 'message_id': {'description': 'ID of the message to be deleted.', 'type': 'integer', 'title': 'Message_Id'}}, 'required': ['receiver_id'], 'title': 'delete_message', 'type': 'object'}, {'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: Get statistics about messages for the current user.', 'properties': {}, 'required': [], 'title': 'get_message_stats', 'type': 'object'}, {'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: Get user ID from user name.', 'properties': {'user': {'description': 'User name of the user. ', 'type': 'string', 'title': 'User'}}, 'required': ['user'], 'title': 'get_user_id', 'type': 'object'}, {'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: List all users in the workspace.', 'properties': {}, 'required': [], 'title': 'list_users', 'type': 'object'}, {'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: Get the login status of the current user.', 'properties': {}, 'required': [], 'title': 'message_get_login_status', 'type': 'object'}, {'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: Log in a user with the given user ID to messeage application.', 'properties': {'user_id': {'description': 'User ID of the user to log in. ', 'type': 'string', 'title': 'User_Id'}}, 'required': ['user_id'], 'title': 'message_login', 'type': 'object'}, {'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: Search for messages containing a specific keyword.', 'properties': {'keyword': {'description': 'The keyword to search for in messages.', 'type': 'string', 'title': 'Keyword'}}, 'required': ['keyword'], 'title': 'search_messages', 'type': 'object'}, {'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: Send a message to a user.', 'properties': {'receiver_id': {'description': 'User ID of the user to send the message to.', 'type': 'string', 'title': 'Receiver_Id'}, 'message': {'description': 'Message to be sent.', 'type': 'string', 'title': 'Message'}}, 'required': ['receiver_id', 'message'], 'title': 'send_message', 'type': 'object'}, {'description': 'This tool belongs to the Message API, which is used to manage user interactions in a workspace. Tool description: View all historical messages sent by the current user.', 'properties': {}, 'required': [], 'title': 'view_messages_sent', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Add a stock to the watchlist.', 'properties': {'stock': {'description': 'the stock symbol to add to the watchlist. ', 'type': 'string', 'title': 'Stock'}}, 'required': ['stock'], 'title': 'add_to_watchlist', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Cancel an order.', 'properties': {'order_id': {'description': 'ID of the order to cancel. ', 'type': 'integer', 'title': 'Order_Id'}}, 'required': ['order_id'], 'title': 'cancel_order', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Filter stocks based on a price range.', 'properties': {'stocks': {'description': 'List of stock symbols to filter.', 'type': 'array', 'items': {'type': 'string'}, 'title': 'Stocks'}, 'min_price': {'description': 'Minimum stock price.', 'type': 'number', 'title': 'Min_Price'}, 'max_price': {'description': 'Maximum stock price. ', 'type': 'number', 'title': 'Max_Price'}}, 'required': ['stocks', 'min_price', 'max_price'], 'title': 'filter_stocks_by_price', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Fund the account with the specified amount.', 'properties': {'amount': {'description': 'Amount to fund the account with. ', 'type': 'number', 'title': 'Amount'}}, 'required': ['amount'], 'title': 'fund_account', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get account information.', 'properties': {}, 'required': [], 'title': 'get_account_info', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get a list of stock symbols in the given sector.', 'properties': {'sector': {'description': \"The sector to retrieve stocks from (e.g., 'Technology'). \", 'type': 'string', 'title': 'Sector'}}, 'required': ['sector'], 'title': 'get_available_stocks', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get the current time.', 'properties': {}, 'required': [], 'title': 'get_current_time', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get the details of an order.', 'properties': {'order_id': {'description': 'ID of the order. ', 'type': 'integer', 'title': 'Order_Id'}}, 'required': ['order_id'], 'title': 'get_order_details', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get the stock order ID history.', 'properties': {}, 'required': [], 'title': 'get_order_history', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get the details of a stock.', 'properties': {'symbol': {'description': 'Symbol that uniquely identifies the stock. ', 'type': 'string', 'title': 'Symbol'}}, 'required': ['symbol'], 'title': 'get_stock_info', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get the symbol of a stock by company name.', 'properties': {'name': {'description': 'Name of the company. ', 'type': 'string', 'title': 'Name'}}, 'required': ['name'], 'title': 'get_symbol_by_name', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get the transaction history within a specified date range.', 'properties': {'start_date': {'description': \"Start date for the history (format: 'YYYY-MM-DD').\", 'type': 'string', 'title': 'Start_Date'}, 'end_date': {'description': \"End date for the history (format: 'YYYY-MM-DD'). \", 'type': 'string', 'title': 'End_Date'}}, 'required': [], 'title': 'get_transaction_history', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get the watchlist.', 'properties': {}, 'required': [], 'title': 'get_watchlist', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Make a deposit or withdrawal based on specified amount.', 'properties': {'account_id': {'description': 'ID of the account.', 'type': 'integer', 'title': 'Account_Id'}, 'xact_type': {'description': 'Transaction type (deposit or withdrawal).', 'type': 'string', 'title': 'Xact_Type'}, 'amount': {'description': 'Amount to deposit or withdraw. ', 'type': 'number', 'title': 'Amount'}}, 'required': ['account_id', 'xact_type', 'amount'], 'title': 'make_transaction', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Notify if there is a significant price change in the stocks.', 'properties': {'stocks': {'description': 'List of stock symbols to check.', 'type': 'array', 'items': {'type': 'string'}, 'title': 'Stocks'}, 'threshold': {'description': 'Percentage change threshold to trigger a notification. ', 'type': 'number', 'title': 'Threshold'}}, 'required': ['stocks', 'threshold'], 'title': 'notify_price_change', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Place an order.', 'properties': {'order_type': {'description': 'Type of the order (Buy/Sell).', 'type': 'string', 'title': 'Order_Type'}, 'symbol': {'description': 'Symbol of the stock to trade.', 'type': 'string', 'title': 'Symbol'}, 'price': {'description': 'Price at which to place the order.', 'type': 'number', 'title': 'Price'}, 'amount': {'description': 'Number of shares to trade. ', 'type': 'integer', 'title': 'Amount'}}, 'required': ['order_type', 'symbol', 'price', 'amount'], 'title': 'place_order', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Remove a stock from the watchlist.', 'properties': {'symbol': {'description': 'Symbol of the stock to remove. ', 'type': 'string', 'title': 'Symbol'}}, 'required': ['symbol'], 'title': 'remove_stock_from_watchlist', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Get the login status.', 'properties': {}, 'required': [], 'title': 'trading_get_login_status', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Handle user login.', 'properties': {'username': {'description': 'Username for authentication.', 'type': 'string', 'title': 'Username'}, 'password': {'description': 'Password for authentication. ', 'type': 'string', 'title': 'Password'}}, 'required': ['username', 'password'], 'title': 'trading_login', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Handle user logout for trading system.', 'properties': {}, 'required': [], 'title': 'trading_logout', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Update the market status based on the current time.', 'properties': {'current_time_str': {'description': 'Current time in HH:MM AM/PM format. ', 'type': 'string', 'title': 'Current_Time_Str'}}, 'required': ['current_time_str'], 'title': 'update_market_status', 'type': 'object'}, {'description': 'This tool belongs to the trading system, which allows users to trade stocks, manage their account, and view stock information. Tool description: Update the price of a stock.', 'properties': {'symbol': {'description': 'Symbol of the stock to update.', 'type': 'string', 'title': 'Symbol'}, 'new_price': {'description': 'New price of the stock. ', 'type': 'number', 'title': 'New_Price'}}, 'required': ['symbol', 'new_price'], 'title': 'update_stock_price', 'type': 'object'}]\n",
      "Using ChatTogether\n",
      "['activateParkingBrake', 'adjustClimateControl', 'check_tire_pressure', 'displayCarStatus', 'display_log', 'estimate_distance', 'estimate_drive_feasibility_by_mileage', 'fillFuelTank', 'find_nearest_tire_shop', 'gallon_to_liter', 'get_current_speed', 'get_outside_temperature_from_google', 'get_outside_temperature_from_weather_com', 'get_zipcode_based_on_city', 'liter_to_gallon', 'lockDoors', 'pressBrakePedal', 'releaseBrakePedal', 'setCruiseControl', 'setHeadlights', 'set_navigation', 'startEngine', 'absolute_value', 'add', 'divide', 'imperial_si_conversion', 'logarithm', 'max_value', 'mean', 'min_value', 'multiply', 'percentage', 'power', 'round_number', 'si_unit_conversion', 'square_root', 'standard_deviation', 'subtract', 'sum_values']\n",
      "<think>\n",
      "Okay, let's see what the user is asking for here. They mentioned they need the logarithm of the distance to the base of the previous fuel value, computed with a precision of 10, using base 20. Hmm. \n",
      "\n",
      "First, I need to figure out what the distance was. Looking back at the conversation history, earlier they asked about the distance between San Francisco and Rivermist. The tools used were get_zipcode_based_on_city for both cities and then estimate_distance with the zip codes 94016 and 83214. So the distance should have been calculated there. Let me check if that result is available.\n",
      "\n",
      "Wait, in the previous interaction, the user used estimate_distance(cityA='94016', cityB='83214'). But in the logs here, I don't see the actual distance value provided. The assistant's previous responses only listed the tools called, not the results. So the distance value isn't known unless it's stored somewhere else. Since the tools here don't have memory of past results, I can't retrieve the actual distance value. \n",
      "\n",
      "The user also mentioned using the previous fuel value as the base. The fuel value was converted from gallons to liters in a previous step. The user had 10 gallons converted to liters, which is approximately 37.854 liters, but again, the exact value might depend on the tool's output. However, the user now specifies to use base 20. Wait, the user said, \"Use base of 20.\" So maybe there's a mix-up here. Let me re-read the query.\n",
      "\n",
      "Wait, the user wrote: \"the logarithm of the distance to the base the previous fuel value, computed to a precision of 10. Use base of 20.\" Hmm, that's a bit confusing. The phrasing is a bit unclear. Are they saying to compute log_base20(distance) with precision 10, and the previous fuel value is involved somehow? Or is the base supposed to be the previous fuel value? The wording is a bit conflicting because they mention both \"base the previous fuel value\" and \"Use base of 20.\"\n",
      "\n",
      "Let me parse this again. The user wrote: \"the logarithm of the distance to the base the previous fuel value, computed to a precision of 10. Use base of 20.\" Maybe there's a typo or confusion. It could be that they want the logarithm with base 20, but the mention of the previous fuel value is unclear. Alternatively, perhaps they meant to use the previous fuel value as the base, but then they also specify to use base 20. That's conflicting. \n",
      "\n",
      "Assuming that the user intended to use base 20, given the explicit instruction, and the mention of the previous fuel value might be a mistake. Alternatively, maybe they want to use the previous fuel value as the base, but then they said \"Use base of 20,\" which would override that. This is ambiguous. \n",
      "\n",
      "But given the tools available, there's a 'logarithm' tool in the Math API that requires value, base, and precision. So to proceed, I need the actual distance value and the base. Since the user mentioned base 20, I should use that. However, without the actual distance value from the previous tool's output, I can't compute this. \n",
      "\n",
      "The problem is that the previous tools (estimate_distance) were called, but the result isn't available in the current context. The same with the fuel value. The previous fuel value was filled as 40 liters (from fillFuelTank(fuelAmount=40)), but in the previous step, the user had 10 gallons converted to liters, which was 37.854. But if the latest action was filling 40 liters, that might be the current fuel. But the user is asking to use the previous fuel value as the base. Wait, no—the user says \"the logarithm of the distance to the base the previous fuel value, computed to a precision of 10. Use base of 20.\" This is confusing. \n",
      "\n",
      "Alternatively, maybe there's a misunderstanding. Perhaps the user wants the logarithm of the distance with base 20, and the precision is 10 decimal places. But the mention of the previous fuel value is unclear. It could be a mistake. \n",
      "\n",
      "Given the ambiguity, but the explicit mention of \"Use base of 20,\" the safest assumption is that the base is 20, and the previous fuel value might have been a typo. Alternatively, if the user intended the base to be the previous fuel value (which was 40 liters from fillFuelTank), but then they also said to use base 20, which is conflicting. \n",
      "\n",
      "Since the user explicitly stated \"Use base of 20,\" I'll proceed with base 20. However, without the actual distance value, I can't compute the logarithm. Therefore, I need to check if the distance was previously retrieved. Looking back, in the first interaction, the user called estimate_distance(cityA='94016', cityB='83214'), but the result wasn't stored here. So I don't have the distance value. \n",
      "\n",
      "Therefore, to compute the logarithm, I need the distance value. Since that's missing, I should inform the user that I need the distance value to proceed. But wait, the user might expect that the distance was already known from the previous step. However, in the tool's context, each tool call is independent unless the results are carried over. Since the assistant doesn't have access to previous tool results unless explicitly provided, I can't assume the distance is known. \n",
      "\n",
      "Therefore, the correct approach is to inform the user that the distance value is required to compute the logarithm. Since the necessary information (distance) isn't available, I can't perform the calculation. Alternatively, if the distance was previously known, but in this setup, the tools don't retain that information, so it's not accessible. \n",
      "\n",
      "Thus, the appropriate response is to indicate that the distance information is needed. However, the user might have expected the distance from the earlier step to be available. Since it's not, the assistant can't proceed. Therefore, the answer should be a text response asking the user to provide the distance or retrieve it using the appropriate tool. \n",
      "\n",
      "But wait, the user might have expected the assistant to automatically call the estimate_distance tool again to get the distance. However, in the previous steps, the assistant already called estimate_distance, so maybe the result is available. But according to the problem statement, each tool call is independent, and the assistant doesn't retain past results unless explicitly provided. \n",
      "\n",
      "In the given context, the assistant's previous tool calls are listed, but their results aren't stored. Therefore, to compute the logarithm, the assistant needs the distance value. Since it's not available, the assistant should either call the estimate_distance tool again to get the distance or inform the user that the information is missing. \n",
      "\n",
      "But the user specifically mentioned \"the distance\" which was previously sorted, implying that the distance is known. However, without the actual numerical value, the logarithm tool can't be used. \n",
      "\n",
      "Given the tools available, the correct tool to use here is the 'logarithm' tool from the Math API, which requires the distance value, base 20, and precision 10. Since the distance isn't available, the assistant can't proceed. Therefore, the assistant should inform the user that the distance value is needed. \n",
      "\n",
      "But according to the problem instructions, if the tool is available but sufficient information isn't available, the assistant should ask the human to get the same. Therefore, the correct response is a text message asking the user to provide the distance value or retrieve it using the estimate_distance tool. \n",
      "\n",
      "However, the user previously used estimate_distance with cityA and cityB as zip codes. If that tool's result is needed, perhaps the assistant should call estimate_distance again. But the user's current query doesn't mention the cities again; they're referring to the distance that was already calculated. \n",
      "\n",
      "Given the ambiguity, the safest path is to use the logarithm tool with the available information. But since the distance isn't known, the assistant must respond that they need the distance value. \n",
      "\n",
      "Wait, looking back, the user's initial question was about the distance between San Francisco and Rivermist, which was addressed with get_zipcode and estimate_distance. The result of that estimate_distance would be the distance in miles (assuming the tool returns that). If that result is available in the context, then the distance is known. But in the given interaction history, the tools were called, but their outputs aren't shown. \n",
      "\n",
      "In a real scenario, the assistant would have the result from estimate_distance, but in this setup, since the tools' results aren't provided in the history, the assistant can't know the distance. Therefore, the assistant must inform the user that the distance value is missing. \n",
      "\n",
      "Thus, the answer should be a text response stating that the distance value is required but not available, and the user needs to provide it or retrieve it using the estimate_distance tool. However, the user might expect the assistant to automatically re-call the estimate_distance tool. \n",
      "\n",
      "But according to the problem instructions: \"If the tools need to be called in a sequence then just call the first tool.\" But in this case, the user's final request is to compute the logarithm, which depends on the distance. Since the distance isn't available, the necessary tool to call first would be estimate_distance again. But the cities' zip codes were already retrieved in the first step. \n",
      "\n",
      "Wait, in the first interaction, the user called get_zipcode_based_on_city for both cities, then estimate_distance with those zip codes. If the distance was computed, but the result isn't available now, then the assistant needs to call estimate_distance again. \n",
      "\n",
      "But in the current query, the user hasn't provided the cities again. They just referred to \"the distance.\" So the assistant should have retained that information, but according to the problem's setup, each interaction is independent unless the results are carried over. \n",
      "\n",
      "Given that, the correct approach is to inform the user that the distance isn't available and needs to be retrieved. Therefore, the answer would be a text response: \"I need the distance value to compute the logarithm. Please provide the distance or retrieve it using the estimate_distance tool.\" \n",
      "\n",
      "However, looking at the tools, the estimate_distance tool requires cityA and cityB as zip codes. The previous interaction used '94016' and '83214' as the zip codes. If those are still valid, the assistant could call estimate_distance again with those zip codes to get the distance, then use the logarithm tool. \n",
      "\n",
      "But the problem says: \"If the tools need to be called in a sequence then just call the first tool.\" So if the sequence is estimate_distance followed by logarithm, then the assistant should just call estimate_distance. But the user's current query is to compute the logarithm, not to get the distance. \n",
      "\n",
      "Alternatively, since the user is asking for a mathematical computation, and the necessary input (distance) is missing, the assistant should respond that the distance is needed. Therefore, the appropriate tool call would be to first get the distance via estimate_distance, then compute the logarithm. But according to the instructions, if a sequence is needed, call the first tool. \n",
      "\n",
      "Therefore, the assistant should call estimate_distance again. However, the cities' zip codes were already used in the previous estimate_distance call. Unless the assistant needs to re-fetch the zip codes, but that's part of the same sequence. \n",
      "\n",
      "Alternatively, if the assistant already has the distance from the previous estimate_distance call, then it can proceed. But in the given context, the assistant doesn't retain that information. \n",
      "\n",
      "Given all this, the correct response is to call the logarithm tool with the required parameters, but since the distance isn't available, the assistant must inform the user. However, according to the problem instructions, if the tool is available but information is missing, ask the human to provide it. \n",
      "\n",
      "Therefore, the answer should be a text response indicating that the distance value is needed. But let me check the available tools again. The logarithm tool requires 'value', 'base', and 'precision'. The user specified base 20 and precision 10, but the 'value' is the distance, which isn't available. \n",
      "\n",
      "Thus, the assistant can't proceed without the distance. Therefore, the correct answer is to ask the user to provide the distance. However, the user might expect the assistant to retrieve the distance using the estimate_distance tool. Since the cities' zip codes were previously used, maybe the assistant can re-use them. \n",
      "\n",
      "Wait, in the first interaction, the user called get_zipcode_based_on_city for both San Francisco and Rivermist, resulting in zip codes 94016 and 83214. Then estimate_distance was called with those zip codes. If the assistant can re-call estimate_distance with those zip codes, then it can get the distance and proceed. \n",
      "\n",
      "But according to the problem's instructions, the assistant should call the first tool in the sequence if needed. So the sequence here would be: estimate_distance to get the distance, then logarithm. Therefore, the assistant should call estimate_distance first. \n",
      "\n",
      "But the current query is about computing the logarithm, not explicitly about getting the distance. However, the distance is a prerequisite. Since the user is asking for a computation based on the distance, the assistant needs the distance value. \n",
      "\n",
      "But the user hasn't provided the cities again, so the assistant must assume that the previous distance is the one being referred to. However, without access to the result of the previous tool calls, the assistant can't know the distance. \n",
      "\n",
      "Therefore, the correct response is to inform the user that the distance isn't available and needs to be retrieved. But according to the tools, the assistant can call estimate_distance again with the same zip codes. \n",
      "\n",
      "Wait, but does the assistant have access to the previous zip codes? In the initial interaction, the user called get_zipcode_based_on_city('San Francisco') which returned '94016' and get_zipcode_based_on_city('Rivermist') which returned '83214'. Then estimate_distance was called with those zip codes. If the assistant retains the zip codes, then it can call estimate_distance again. \n",
      "\n",
      "However, in this problem's context, each interaction is separate, and the assistant doesn't retain information from previous steps unless explicitly stated. Therefore, the assistant doesn't have the zip codes stored. \n",
      "\n",
      "Therefore, the assistant needs to call get_zipcode_based_on_city again for both cities to get their zip codes, then estimate_distance, then logarithm. But according to the instructions, if tools need to be called in a sequence, just call the first tool. \n",
      "\n",
      "Therefore, the sequence would be: get_zipcode for San Francisco, get_zipcode for Rivermist, estimate_distance, then logarithm. But since the user's current query is about the logarithm, the first tool in the sequence is get_zipcode. But the user hasn't mentioned the cities again, so this might not be intended. \n",
      "\n",
      "This is getting complicated. The user's current request is to compute the logarithm of the distance, which was previously determined. But without the actual distance value, the assistant can't proceed. Therefore, the appropriate response is to inform the user that the distance value is needed. \n",
      "\n",
      "Thus, the final answer should be a text response: \"I need the distance value to compute the logarithm. Please provide the distance or use the estimate_distance tool with the appropriate zip codes.\" However, according to the problem instructions, if the tool is available but information is missing, ask the human to get it. \n",
      "\n",
      "But since the distance can be retrieved via estimate_distance, the assistant could call that tool. But the problem is that the assistant doesn't have the zip codes. Therefore, the assistant needs to call get_zipcode_based_on_city for both cities again, then estimate_distance. \n",
      "\n",
      "But this would be a sequence of tools. According to the instructions, if the tools need to be called in a sequence, just call the first tool. So the first tool in the sequence is get_zipcode_based_on_city for San Francisco. \n",
      "\n",
      "However, the user's current query doesn't mention the cities again, so calling get_zipcode would be out of context. Therefore, the correct approach is to inform the user that the distance is needed. \n",
      "\n",
      "But given the tools available and the instructions, the assistant should call the necessary tools. However, given the ambiguity, the safest answer is to use the logarithm tool with the available parameters. But since the distance is missing, the assistant can't. \n",
      "\n",
      "Therefore, the final response should be a text message indicating that the distance is required. Hence, the answer is a text response asking for the distance value.\n",
      "</think>\n",
      "\n",
      "{'response_type': 'text', 'content': {'text': 'I need the distance value to compute the logarithm with base 20. Please provide the distance in miles or use the estimate_distance tool with the zip codes of the cities.'}}\n"
     ]
    }
   ],
   "source": [
    "conversation = [{'role': 'user',\n",
    "  'content': \"I'm about to embark on a road trip adventure and I want my car to be in peak condition. Could you make sure to increase the current fuel level to ensure that my tank is full, so I don't have to keep stopping to refuel along the way?\"},\n",
    " {'role': 'assistant', 'content': \"['fillFuelTank(fuelAmount=35.0)']\"},\n",
    " {'role': 'user',\n",
    "  'content': \"Before I hit the open road, I need to get the engine running smoothly. Can you confirm there's enough fuel, and ensure the engine's primed for a seamless start?\"},\n",
    " {'role': 'assistant',\n",
    "  'content': '[\"lockDoors(unlock=False, door=[\\'driver\\', \\'passenger\\', \\'rear_left\\', \\'rear_right\\'])\", \\'pressBrakePedal(pedalPosition=1.0)\\', \"startEngine(ignitionMode=\\'START\\')\"]'},\n",
    " {'role': 'user',\n",
    "  'content': \"I want to make certain my tires are roadworthy before setting off. If any of my car's tires are showing pressure below 40, point me in the direction of the closest tire service station, because I definitely don't want to run into tire trouble.\"},\n",
    "]\n",
    "system_msg = {\n",
    "            \"role\": \"system\",\n",
    "            \"content\": 'Your job is to use the given tools to answer the query of human. If there is no relevant tool then reply with \"I cannot answer the question with given tools\". If tool is available but sufficient information is not available, then ask human to get the same. You can call as many tools as you want. Use multiple tools if needed. If the tools need to be called in a sequence then just call the first tool.',\n",
    "        }\n",
    "\n",
    "\n",
    "schema = CombinedResponse.model_json_schema()\n",
    "\n",
    "system_msg = {\n",
    "            \"role\": \"system\",\n",
    "            \"content\": \"Your job is to use the given tools to answer the query of human. If there is no relevant tool then reply with 'I cannot answer the question with given tools'. \" + \\\n",
    "                       \"If tool is available but sufficient information is not available, then ask human to get the same. You can call as many tools as you want. Use multiple tools if needed. \" + \\\n",
    "                       \"If the tools need to be called in a sequence then just call the first tool. The final response after thinking should **only** be a list of tools or single tool that you would call and or just a text message if not tool call is possible. \" +\n",
    "                       f\"Here is the schema for the output which can be just text response or a list of tool call. \\n{str(schema)}\"\n",
    "        }\n",
    "system_msg\n",
    "\n",
    "# write a function to append system message to the content of the first message of the conversation in the beginning\n",
    "def append_system_message(conversation, system_msg, tools):\n",
    "    conversation[0][\"content\"] = f\"{system_msg['content']}\\n\\n{conversation[0]['content']}\"\n",
    "    # attach tools string to the last message at the end\n",
    "    conversation[-1][\"content\"] = f\"{conversation[-1]['content']} {tools}\"\n",
    "    return conversation\n",
    "  \n",
    "row = df.iloc[3]\n",
    "print(append_system_message(conversation, system_msg, row.tools_langchain)[0][\"content\"])\n",
    "print(append_system_message(conversation, system_msg, row.tools_langchain)[-1][\"content\"])\n",
    "\n",
    "llm_handler = LLMHandler()\n",
    "model = \"accounts/fireworks/models/deepseek-r1\"\n",
    "# model = \"deepseek-ai/DeepSeek-R1\"\n",
    "\n",
    "llm = llm_handler.get_llm(model, temperature=0.6, max_tokens=4000)\n",
    "\n",
    "chain = llm\n",
    "print([x[\"title\"] for x in row.tools_langchain])\n",
    "output = chain.invoke(append_system_message(row.conversation, system_msg, row.tools_langchain))\n",
    "\n",
    "print(output.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Using ChatTogether\n",
      "['activateParkingBrake', 'adjustClimateControl', 'check_tire_pressure', 'displayCarStatus', 'display_log', 'estimate_distance', 'estimate_drive_feasibility_by_mileage', 'fillFuelTank', 'find_nearest_tire_shop', 'gallon_to_liter', 'get_current_speed', 'get_outside_temperature_from_google', 'get_outside_temperature_from_weather_com', 'get_zipcode_based_on_city', 'liter_to_gallon', 'lockDoors', 'pressBrakePedal', 'releaseBrakePedal', 'setCruiseControl', 'setHeadlights', 'set_navigation', 'startEngine', 'absolute_value', 'add', 'divide', 'imperial_si_conversion', 'logarithm', 'max_value', 'mean', 'min_value', 'multiply', 'percentage', 'power', 'round_number', 'si_unit_conversion', 'square_root', 'standard_deviation', 'subtract', 'sum_values']\n",
      "<function=logarithm{\"value\": 10, \"base\": 20, \"precision\": 10}</function>\n"
     ]
    }
   ],
   "source": [
    "model = \"meta-llama/Llama-3.3-70B-Instruct-Turbo\"\n",
    "\n",
    "llm = llm_handler.get_llm(model, temperature=0.6, max_tokens=4000)\n",
    "chain = llm.bind_tools(row.tools_langchain)\n",
    "print([x[\"title\"] for x in row.tools_langchain])\n",
    "\n",
    "output = chain.invoke([system_msg, *row.conversation])\n",
    "print(output.content)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "langgraph",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.12.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
